package com.jike.noobmoney.mvp.view.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.image.imagepicker.view.SuperCheckBox;
import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.LimiteEntity;
import com.jike.noobmoney.entity.MoneyEntity;
import com.jike.noobmoney.entity.WXEntity;
import com.jike.noobmoney.mvp.presenter.PayPresenter;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.rxbus.RxBusRoute;
import com.jike.noobmoney.rxbus.RxEvent;
import com.jike.noobmoney.util.AppUtils;
import com.jike.noobmoney.util.Logger;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.jike.noobmoney.wxapi.PayResult;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Create by xuke on 2019/03/03
 * 充值中心
 */
public class ChongZhiActivity extends BaseActivity implements IView {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ck_wx)
    ImageView ckWx;
    @BindView(R.id.ck_zfb)
    ImageView ckZfb;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.et_chongzhi_money)
    EditText etChongzhiMoney;
    @BindView(R.id.checkbox)
    SuperCheckBox checkbox;
    private UserPresenter userPresenter;
    private String userid;
    private MoneyEntity.UserBean userBean;
    private boolean isWeiXin = true;
    private PayPresenter payPresenter;
    private IWXAPI iwxapi;
    public int isFirst=0;
    public String onetype="";
    public double money;

    @Override
    protected int layoutResID() {
        return R.layout.activity_chongzhi;
    }

    @Override
    protected void initData() {
        tvTitle.setText("充值中心");
        userPresenter = new UserPresenter(this);
        payPresenter = new PayPresenter(this);
        iwxapi = WXAPIFactory.createWXAPI(this, ConstantValue.Wechat_Appid, true);
        iwxapi.registerApp(ConstantValue.Wechat_Appid);
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        isFirst= SPUtils.getInstance().getInt(ConstantValue.SpType.isfirst,0);
        changeUi(true);
        refreshData();
        zhifulimit();
    }
    /**
     * 如果要全屏,重写这个方法返回false
     */
    public Boolean isfits() {
        return true;
    }

    /**
     * 如果要白色主题,重写这个方法返回false
     */
    public boolean ismain() {
        return true;
    }
    /**
     * 获取余额
     */
    private void refreshData() {
        showProgress();
        userPresenter.moneyView(userid, ConstantValue.RequestKey.getMoneyView);
    }

    @OnClick({R.id.iv_back, R.id.ll_mingxi, R.id.ll_wx, R.id.ll_zfb, R.id.tv_chongzhi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_mingxi:
                ShouZhiActivity.startAction(context, 0);
                break;
            case R.id.ll_wx:
                changeUi(true);
                break;
            case R.id.ll_zfb:
                changeUi(false);
                break;
            case R.id.tv_chongzhi:
                if (AppUtils.isFastClick()) {
                    return;
                }
                if (isPer()) {
                    if (isWeiXin) {
                        //微信
                        weixin();
                    } else {
                        //支付宝
                        zhifubao();
                    }
                }
                break;
        }
    }

    /**
     * 获取支付限制
     */
    private void zhifulimit() {
        showProgress();
        payPresenter.zfbLimite(userid,ConstantValue.RequestKey.limite);
    }

    /**
     * 支付宝
     */
    private void zhifubao() {
        showProgress();
        String money = etChongzhiMoney.getText().toString().trim();
        payPresenter.zfbPay(userid, money, ConstantValue.RequestKey.zhifubao);
    }

    /**
     * 微信
     */
    private void weixin() {
        showProgress();
        String money = etChongzhiMoney.getText().toString().trim();
        payPresenter.wxPay(userid, money, ConstantValue.RequestKey.weixin);
    }

    private void changeUi(boolean isWeiXin) {
        this.isWeiXin = isWeiXin;
        ckWx.setSelected(isWeiXin);
        ckZfb.setSelected(!isWeiXin);
    }

    private boolean isPer() {
        if (TextUtils.isEmpty(etChongzhiMoney.getText().toString())) {
            ToastUtils.showShortToastSafe("请填写充值金额");
            etChongzhiMoney.requestFocus();
            return false;
        }
        if(onetype.equals("1")){
          Double moneyinput=  Double.parseDouble(etChongzhiMoney.getText().toString());
          if(moneyinput<money){
              ToastUtils.showShortToastSafe("充值必须大于"+money+"元");
              return false;
          }
        }


        if (!checkbox.isChecked()) {
            ToastUtils.showShortToastSafe("请先同意充值协议");
            return false;
        }
        return true;
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.getMoneyView.equals(actionType)) {
            //获取用户余额
            userBean = (MoneyEntity.UserBean) data;
            tvMoney.setText("" + userBean.getRwmoney());
        }
        if (ConstantValue.RequestKey.limite.equals(actionType)) {
          LimiteEntity entity=  (LimiteEntity)data;
            onetype= entity.getOnetype();
            money=entity.getMoney();
        }

        if (ConstantValue.RequestKey.weixin.equals(actionType)) {
            WXEntity wxEntity = (WXEntity) data;
            Logger.e("xuke", "wx=" + wxEntity.toString());
            PayReq request = new PayReq();
            request.appId = wxEntity.getAppid();
            request.partnerId = wxEntity.getPartnerid();
            request.prepayId = wxEntity.getPrepayid();
            request.packageValue = wxEntity.getPackageX();
            request.nonceStr = wxEntity.getNoncestr();
            request.timeStamp = wxEntity.getTimestamp();
            request.sign = wxEntity.getPaySign();
            iwxapi.sendReq(request);
        } else if (ConstantValue.RequestKey.zhifubao.equals(actionType)) {
            String orderInfo = (String) data;
            Logger.e("xuke", "info = " + orderInfo);

            Runnable payRunnable = () -> {
                PayTask alipay = new PayTask(ChongZhiActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg1 = new Message();
                msg1.what = 100;
                msg1.obj = result;
                mHandler.sendMessage(msg1);
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();

        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100: {
                    //Map<String, String> result = (Map<String, String>) msg.obj;
                    PayResult result = new PayResult((Map<String, String>) msg.obj);
                    Logger.e("xuke", "result=" + result);
                    if (result.getResultStatus().equals("9000")) {
                        ToastUtils.showShortToastSafe("支付成功");
                        SPUtils.getInstance().put(ConstantValue.SpType.isfirst,0);
                        refreshData(); //支付宝支付成功
                        zhifulimit();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public void onFailed(String code, String msg) {
        dismissProgress();
        ToastUtils.showShortToastSafe(msg);
    }

    @Override
    protected boolean isRegistRxBus() {
        return true;
    }

    /**
     * 注册订阅事件
     */
    protected void receiveEvent(RxEvent rxEvent) {
        switch (rxEvent.busName) {
            case RxBusRoute.WEIXIN:
                SPUtils.getInstance().put(ConstantValue.SpType.isfirst,0);
                refreshData(); //微信支付成功  刷新页面
                zhifulimit();
                break;
        }
    }
}
